/* Gluten Library -- Utility
 *
 * A grab bag of useful types and functionality. Anything that is too small to
 * have its own place will likely be stuffed here.
 *
 * $AUTHOR$    res
 * $UPDATE$    r31
 */

/* LICENSES ********************************************************************

Copyright (c) 2013- Reuben E. Smith

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*******************************************************************************/


#ifndef GLUTEN_UTILITY_HPP
#define GLUTEN_UTILITY_HPP

// res: One of these C headers includes a glibc header somewhere that defines 
//      two macros: `major` and `minor`. Who thought a system-wide macro using 
//      all lowercase named after common words was a nice thing to do? Sigh.
#include <cfloat>
#include <cmath>
#include <cstdint>
#include <string>
#include <vector>


namespace Gluten
{
   const double PI = 3.141592653589793;
   const double TO_DEG = 180.0 / PI;
   const double TO_RAD = PI / 180.0;


   //! \brief Clamp a value within a given range.
   //! \param[in]       value          the value to clamp
   //! \param[in]       min            range minimum, inclusive
   //! \param[in]       max            range maximum, inclusive
   //! \return          the clamped value: value, min, or max
   template < typename T, typename U, typename V >
   T clamp(T value, U min, V max)
   {
      // res: Some funky casting might go on with the three different types.
      //      Watch it.
      return (value < min) ? min : ((value > max) ? max : value);
   }



   //! \struct Color
   //! \brief Structure representing an RGBA color.
   struct Color
   {
      static const Color RED;
      static const Color GREEN;
      static const Color BLUE;
      static const Color YELLOW;
      static const Color CYAN;
      static const Color MAGENTA;
      static const Color BLACK;
      static const Color WHITE;
      static const Color GREY;

      uint_least8_t r;
      uint_least8_t g;
      uint_least8_t b;
      uint_least8_t a;


      //! \brief Default constructor. Initializes color to black.
      Color() : r(0), g(0), b(0), a(0) {}


      //! \brief Copy constructor. Copies channel values from another color.
      //! \param[in]    other          the color to copy
      Color(const Color& other)
         : r(other.r), g(other.g), b(other.b), a(other.a)
      {}


      //! \brief Parameter constructor. Copies channel values from an array.
      //! \param[in]  values               array to copy
      //-------------------------------------------------------------------//
      Color(const float values[4])
      {
         rf(values[0]);
         gf(values[1]);
         bf(values[2]);
         af(values[3]);
      }


      Color(const double values[4])
      {
         rd(values[0]);
         gd(values[1]);
         bd(values[2]);
         ad(values[3]);
      }
      //-------------------------------------------------------------------//


      //! \brief Parameter constructor. Initializes color with given values.
      //! \param[in]    r              red channel
      //! \param[in]    g              green channel
      //! \param[in]    b              blue channel
      //! \param[in]    a              alpha channel
      Color(uint_least8_t r, uint_least8_t g, uint_least8_t b, uint_least8_t a) 
         : r(r), g(g), b(b), a(a) 
      {}


      //! \brief Assignment operator. Copies channel values from another color.
      //! \param[in]    other          the color to copy
      //! \return       this color
      Color& operator=(const Color& other)
      {
         r = other.r;
         g = other.g;
         b = other.b;
         a = other.a;

         return *this;
      }


      //! \brief Test if another color is equivalent to this one.
      //! \param[in]    other          the color to compare
      //! \return       true if all channel values are equal
      bool operator==(const Color& other) const
      {
         return (r == other.r) && (g == other.g) && 
                (b == other.b) && (a == other.a);
      }


      //! \brief Test if another color is not equivalent to this one.
      //! \param[in]    other          the color to compare
      //! \return       true if any channel values are unequal
      bool operator!=(const Color& other) const
      {
         return !operator==(other);
      }


      //! \brief Floating-point channel accessors.
      //! \param[in]    v              channel value from [0, 1]
      //! \return       channel value as float clamped to [0, 1]
      //---------------------------------------------------------------------//
      inline float rf() const { return r / 255.0f; }
      inline void rf(float v) { r = static_cast<uint_least8_t>(clamp(v, 0.f, 1.f) * 255); }
      inline float gf() const { return g / 255.0f; }
      inline void gf(float v) { g = static_cast<uint_least8_t>(clamp(v, 0.f, 1.f) * 255); }
      inline float bf() const { return b / 255.0f; }
      inline void bf(float v) { b = static_cast<uint_least8_t>(clamp(v, 0.f, 1.f) * 255); }
      inline float af() const { return a / 255.0f; }
      inline void af(float v) { a = static_cast<uint_least8_t>(clamp(v, 0.f, 1.f) * 255); }

      inline double rd() const { return r / 255.0; }
      inline void rd(double v) { r = static_cast<uint_least8_t>(clamp(v, 0., 1.) * 255); }
      inline double gd() const { return g / 255.0; }
      inline void gd(double v) { g = static_cast<uint_least8_t>(clamp(v, 0., 1.) * 255); }
      inline double bd() const { return b / 255.0; }
      inline void bd(double v) { b = static_cast<uint_least8_t>(clamp(v, 0., 1.) * 255); }
      inline double ad() const { return a / 255.0; }
      inline void ad(double v) { a = static_cast<uint_least8_t>(clamp(v, 0., 1.) * 255); }
      //---------------------------------------------------------------------//
   };


   //! \brief Test for floating-point relative equality.
   //! \param[in]       a              the first value
   //! \param[in]       b              the second value
   //! \return          true iff a is relatively equal to b
   //!
   //! Equality tests for floating-point types should not work by comparing
   //! bits as most other types do given the nature of accuracy with fp types.
   //! Use this function to compare floats and doubles to see if they're
   //! relatively equal within some epsilon. Passing a non-floating-point
   //! type will just call operator== on those types.
   //------------------------------------------------------------------------//
   template < typename T, typename U >
   inline bool fpRelativeEqual(T a, U b)
   {
      return a == b;
   }


   template <> bool fpRelativeEqual<float>(float a, float b);
   template <> bool fpRelativeEqual<double>(double a, double b);
   //------------------------------------------------------------------------//
   

   //! \brief Read a file in and return a vector containing its text.
   //! \param[in]       path           path to file to read
   //! \return          a vector containing the lines of the file; vector will
   //!                  be empty if file did not exist or could not be read
   std::vector< std::string > vectorizeFile(const std::string& path);


   //! \brief Split a string into tokens and return a vector of them.
   //! \param[in]       str            the string to split
   //! \param[in]       delim          string of delimiting characters
   //! \return          a vector containing the string's tokens
   std::vector< std::string > tokenizeString(const std::string& str,
      const std::string& delim = " \f\n\r\t\v");


   //! \brief Draw parameterized text within the current viewport.
   //! \param[in]       text           the text to draw
   //! \param[in]       font           freeglut bitmap font to use
   //! \param[in]       x              where to draw the text
   //! \param[in]       y              where to draw the text
   //! \param[in]       color          color to draw font with
   void drawTextAt(const std::string& text, void* font, double x, double y,
      const Color& color = Color::WHITE);


   //! \brief Get millisecond-precision system time.
   //! \return          time in milliseconds
   //!
   //! The internal functions used may wrap around at various points, most
   //! likely near 49 days.
   uintmax_t getSystemTime();


   //! \brief Get millisecond-precision program time.
   //! \return          time since program start in milliseconds
   //!
   //! The internal functions used may wrap around at various points, most
   //! likely near 49 days.
   uintmax_t getProgramTime();


   //! \brief System time when program started.
   const uintmax_t PROGRAM_START_TIME = getSystemTime();
}

#endif

